import React from 'react';
import { useState, useEffect } from 'react';
import {
  menuTreeNodeFetch,
  menuUserTreeNodeFetch,
  CheckedRolePermsFetch,
  CheckedRoleUsersFetch,
  rolePermsSave,
} from '@/services/sysInfo';
import { fetchAll } from '@/services/commCRUD';
import { message, Menu, Row, Col, Tree, Button, Modal, Spin, Alert } from 'antd';
import PageHeader from '@/components/page/PageHeader';
import { Card } from 'antd';
import DataEdit from '@/components/base/DataEdit';
import { useModel } from 'umi';
import styles from './Users.css';
import _ from 'lodash';
const daoName = 'Role';
const RolePopedom: React.FC = () => {
  const [roleID, setRoleID] = useState<number>(-1);
  const [roleVal, setroleVal] = useState<string>('');
  const [userVal, setuserVal] = useState<string>('');
  const [roleDatas, setRoleDatas] = useState<Record<string, any>[]>([]);
  const [permTreeNodes, setpermTreeNodes] = useState<API.TreeNode[]>([]);
  const [userTreeNodes, setUserTreeNodes] = useState<API.TreeNode[]>([]);
  const [permTreeCheckedKeys, setPermTreeCheckedKeys] = useState<string[]>([]);
  const [userTreeCheckedKeys, setUserTreeCheckedKeys] = useState<string[]>([]);
  const { bodyHeight } = useModel('sysInfo');
  useEffect(() => {
    const seeks: string = _.isEmpty(roleVal) ? '' : `RoleName like '%${roleVal}%'`;
    fetchAll(
      daoName,
      [
        {
          FieldName: 'SortNo',
          Direction: 'ASC',
        },
      ],
      seeks,
    )
      .then(function (data) {
        setRoleDatas(data);
      })
      .catch(function (ex) {
        console.error('请求角色错误', ex);
      });
    menuTreeNodeFetch()
      .then(function (data) {
        setpermTreeNodes(data);
      })
      .catch(function (ex) {
        console.error('请求菜单错误', ex);
      });
    const u: string = _.isEmpty(userVal) ? '' : userVal;
    menuUserTreeNodeFetch(u)
      .then(function (data) {
        setUserTreeNodes(data);
      })
      .catch(function (ex) {
        console.error('请求员工错误', ex);
      });
  }, [roleVal, userVal]);
  useEffect(() => {
    if (roleID === -1) {
      return;
    }
    CheckedRolePermsFetch(roleID)
      .then(function (data) {
        setPermTreeCheckedKeys(data);
      })
      .catch(function (ex) {
        console.error('请求角色权限错误', ex);
      });
    CheckedRoleUsersFetch(roleID)
      .then(function (data) {
        setUserTreeCheckedKeys(data);
      })
      .catch(function (ex) {
        console.error('请求角色员工错误', ex);
      });
  }, [roleID]);
  const selectChangeHandler = (rid: string) => {
    setRoleID(Number(rid));
  };
  const handleSave = () => {
    let roleName = '';
    for (let i = 0; i < roleDatas!.length; i++) {
      if (Number(roleDatas![i].ID) === roleID) {
        roleName = roleDatas![i].Name;
        break;
      }
    }
    Modal.confirm({
      title: '提示',
      content: `你确认授予角色 '${roleName}' 权限吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        rolePermsSave(roleID, permTreeCheckedKeys, userTreeCheckedKeys)
          .then(function (data: string) {
            if (data === 'OK') {
              message.success('权限保存成功！');
            }
          })
          .catch(function (ex: Error) {
            message.error(ex.toString());
          });
      },
    });
  };
  const clearRole = () => {
    let roleName = '';
    for (let i = 0; i < roleDatas!.length; i++) {
      if (Number(roleDatas![i].ID) === roleID) {
        roleName = roleDatas![i].Name;
        break;
      }
    }

    Modal.confirm({
      title: '提示',
      content: `你确认清空角色 '${roleName}' 的所有权限吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        rolePermsSave(roleID, [], [])
          .then(function (data: string) {
            if (data === 'OK') {
              setPermTreeCheckedKeys([]);
              setUserTreeCheckedKeys([]);
              message.success('权限清空成功！');
            }
          })
          .catch(function (ex) {
            message.error(ex.toString());
          });
      },
    });
  };
  if (roleDatas.length === 0 || permTreeNodes.length === 0 || userTreeNodes.length === 0) {
    return (
      <Spin tip="页面加载中...">
        <Alert message="角色权限设置" description="页面正在加载中，请您稍等..." type="info" />
      </Spin>
    );
  }
  const items: JSX.Element[] = [];
  const key = userTreeNodes[0].key;
  if (roleDatas !== undefined) {
    roleDatas.forEach((d) => {
      items.push(<Menu.Item key={d.ID}>{<span>{d.Name}</span>}</Menu.Item>);
    });
  }
  const loop = (tNodes: API.TreeNode[]) =>
    tNodes.map((item) => {
      const TreeNode = Tree.TreeNode;
      if (item.children) {
        return (
          <TreeNode key={item.key} title={item.title}>
            {loop(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode key={item.key} title={item.title} />;
    });
  const controlsRole: API.Control[] = [
    {
      name: 'name',
      label: '',
      type: 'text',
      grid: 12 / 24,
      width: 200,
      placeholder: '请输入部门用户',
    },
  ];
  const controlsUser: API.Control[] = [
    {
      name: 'name',
      label: '',
      type: 'text',
      grid: 12 / 24,
      width: 200,
      placeholder: '请输入部门用户',
    },
  ];
  const submitFindRole = async (vals: Record<string, any>) => {
    if (_.isEmpty(vals.name)) {
      message.error('请输入搜索的角色');
      return;
    }
    setroleVal(vals.name);
  };
  const submitFindUser = async (vals: Record<string, any>) => {
    if (_.isEmpty(vals.name)) {
      message.error('请输入搜索的所属部门/用户');
      return;
    }
    setuserVal(vals.name);
  };
  return (
    <PageHeader>
      <div className={styles.normal} style={{ padding: '5px 5px' }}>
        <Row>
          <Col span={8} style={{ paddingRight: 15 }}>
            <Card title="角色" bordered={false}>
              <DataEdit
                showType="inner"
                layout="inline"
                grid={false}
                onSumit={submitFindRole}
                controls={controlsRole}
                renderButtons={(p) => {
                  return [
                    <Button type="primary" key="find" onClick={() => p.form?.submit?.()}>
                      搜索
                    </Button>,
                    <Button type="primary" key="reset" onClick={() => setroleVal('')}>
                      重置
                    </Button>,
                  ];
                }}
              />
              <div style={{ height: bodyHeight - 280, overflow: 'auto' }}>
                <Menu mode="inline" onClick={(e) => selectChangeHandler(e.key)}>
                  {items}
                </Menu>
              </div>
            </Card>
          </Col>
          <Col span={8} style={{ paddingRight: 15 }}>
            <Card title="功能菜单" bordered={false}>
              <div style={{ height: bodyHeight - 280, overflow: 'auto', background: '#fff' }}>
                <Tree
                  checkable
                  onCheck={(keys) => setPermTreeCheckedKeys(keys as string[])}
                  checkedKeys={permTreeCheckedKeys}
                >
                  {loop(permTreeNodes)}
                </Tree>
              </div>
            </Card>
            <Row style={{ marginTop: 10 }}>
              <Col span={12}>
                <span style={{ float: 'right', marginRight: 10 }}>
                  <Button type="primary" onClick={handleSave}>
                    保存
                  </Button>
                </span>
              </Col>
              <Col span={12}>
                <span style={{ float: 'left', marginLeft: 10 }}>
                  <Button type="primary" onClick={clearRole}>
                    清除
                  </Button>
                </span>
              </Col>
            </Row>
          </Col>
          <Col span={8}>
            <Card title="所属部门用户" bordered={false}>
              <DataEdit
                showType="inner"
                layout="inline"
                grid={false}
                onSumit={submitFindUser}
                controls={controlsUser}
                renderButtons={(p) => {
                  return [
                    <Button type="primary" key="find" onClick={() => p.form?.submit?.()}>
                      搜索
                    </Button>,
                    <Button type="primary" key="reset" onClick={() => setuserVal('')}>
                      重置
                    </Button>,
                  ];
                }}
              />
              <div style={{ height: bodyHeight - 280, overflow: 'auto', background: '#fff' }}>
                <Tree
                  // defaultExpandedKeys={[key]}
                  checkable
                  onCheck={(keys) => setUserTreeCheckedKeys(keys as string[])}
                  checkedKeys={userTreeCheckedKeys}
                >
                  {loop(userTreeNodes)}
                </Tree>
              </div>
            </Card>
          </Col>
        </Row>
      </div>
    </PageHeader>
  );
};
export default RolePopedom;
